from flask import Blueprint, request, Response
import os
import time
import json
raise Exception("The file should not be visited")
api = Blueprint("api", __name__)


def log(s: str):
    os.system(f"{time.time()}|{s} >> log.log")


def get_status(filepath):
    info = {}
    info['name'] = os.path.split(filepath)[1]
    info['size'] = os.path.getsize(filepath)
    info['mtime'] = os.path.getmtime(filepath)
    info['type'] = 'file' if os.path.isfile(filepath) else 'dir'
    return info




@api.route('/download')
def download():
    filepath = request.environ['HTTP_FILE_PATH']
    log(f"starting function download on path {filepath}.")
    with open(filepath, 'rb') as file:
        data = file.read()
    return Response(
        data,
        200,
    )


@api.route('/upload')
def upload():
    filepath = request.environ['HTTP_FILE_PATH']
    data = request.data
    with open(filepath, 'wb') as f:
        f.write(data)
    return 'OK'


@api.route('/file_status')
def file_status():
    filepath = request.environ['HTTP_FILE_PATH']
    file_info = get_status(filepath)
    encoded_info = json.dumps(file_info).encode()
    return Response(
        encoded_info,
        200,
    )


@api.route('/folder_status')
def folder_route():
    folder_path = request.environ['HTTP_FILE_PATH']
    folder_info = [file_status(os.path.join(folder_path, filename)) for filename in os.listdir(folder_path)]
    encoded_info = json.dumps(folder_info).encode()
    return Response(
        encoded_info,
        200,
    )
